package com.sykj.springboot.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

public class Md5Utils {

//    public static Logger log = LoggerFactory.getLogger(getClass());

    private static final Logger log = LoggerFactory.getLogger(com.sykj.springboot.common.utils.Md5Utils.class);
    /**
     * Md5加密 返回byte[]
     *
     * @param s
     * @return
     */
    public static String md5(String s) {
        MessageDigest algorithm;
        try {
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes("UTF-8"));
            byte[] messageDigest = algorithm.digest();
            return toHex(messageDigest);
        } catch (Exception e) {
            log.info("MD5 Error...", e);
        }
        return null;
    }

    /**
     * byte[]解密 返回string
     *
     * @param hash
     * @return
     */
    private static final String toHex(byte hash[]) {
        if (hash == null) {
            return null;
        }
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++) {
            if ((hash[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString(hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

}
